package com.pray.rabbitmq;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * RabbitConfiguration
 *
 * @author 春江花朝秋月夜
 * @since 2023/11/9 22:14
 */
@Configuration
public class RabbitConfiguration {
    @Bean("directExchange")  //定义交换机Bean，可以很多个
    public Exchange exchange(){
        return ExchangeBuilder.directExchange("amq.direct").build();
    }
    @Bean(name="fanoutExchange")
    public FanoutExchange fanoutExchange(){
        return ExchangeBuilder.fanoutExchange("test.fanout").build();
    }
    @Bean(name = "fanout.queue1")
    public Queue fanoutQueue1(){
        return new Queue("fanout.queue1");
    }
    @Bean(name = "fanout.queue2")
    public Queue fanoutQueue2(){
        return new Queue("fanout.queue2");

    }
    //直连交换机，根据routingKey和bindingKey来实现消息绑定实现消息只能从配对正确的队列和交换机之间传递消息
    @Bean
    public Binding FanoutBinding1(){
        return BindingBuilder.bind(fanoutQueue1()).to(fanoutExchange());
    }
    @Bean
    public Binding FanoutBinding2(){
        return BindingBuilder.bind(fanoutQueue2()).to(fanoutExchange());
    }
    //转换为Json实体的Bean,当需要传输实体的消息是需要解析json
    @Bean(name = "Jackson2JsonMessageConverter")
    public Jackson2JsonMessageConverter jsonMessageConverter(){
        return new Jackson2JsonMessageConverter();
    }
    //更改Spring-RabbitMq的默认（JDK序列化）消息转换器
    @Bean
    MessageConverter messageConverter(){
        //Jackon2Son序列化
        return new Jackson2JsonMessageConverter();
    }
    @Resource
    private CachingConnectionFactory connectionFactory;

    //监听容器
    @Bean(name = "listenerContainer")
    public SimpleRabbitListenerContainerFactory listenerContainer(){
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setPrefetchCount(1);   //将PrefetchCount设定为1表示一次只能取一个
        return factory;
    }
}
